package com.powernode.controller;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.powernode.config.ServerInfoConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashSet;

/**
 * 内容:
 * 作者: cy
 */
@RestController
@Api(tags = "文件管理接口")
@RequestMapping("admin/file")
public class FileController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private ServerInfoConfig serverInfoConfig;


    @PostMapping("upload/element")
    @ApiOperation("文件上传")
    public ResponseEntity<String> doUpload(@RequestParam MultipartFile file) {
        long size = file.getSize();
        // 是文件真实名称
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀名
        String fileExt = StringUtils.getFilenameExtension(originalFilename);
        // 这个是 form表单的 input type=file  name = "aaa"
        String name = file.getName();
        // 上传
        StorePath storePath = null;
        try {
            storePath = fastFileStorageClient.uploadFile(file.getInputStream(), size, fileExt, new HashSet<>());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fullPath = storePath.getFullPath();
        return ResponseEntity.ok(serverInfoConfig.getSeverHost() + fullPath);
    }


}
